import axios, {
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from "axios";
const defaultConfig = {
  timeout: 5000,
  baseUrl: "",
};
class Http {
  constructor() {
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }
  private static axiosInstance = axios.create(defaultConfig);
  // 请求拦截
  private httpInterceptorsRequest() {
    Http.axiosInstance.interceptors.request.use(
      //  处理成功的请求
      (config: InternalAxiosRequestConfig) => {
        return config;
      },
      //   处理失败的请求
      (error) => {
        return Promise.reject(error);
      }
    );
  }
  // 响应拦截
  private httpInterceptorsResponse() {
    Http.axiosInstance.interceptors.response.use(
      // 处理成功的响应
      (response: AxiosResponse) => {
        return response;
      },
      // 处理失败的响应
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  // 封装请求
  // get请求
  //   T是泛型
  public httpRequestGet<T>(
    url: string,
    params: AxiosRequestConfig
  ): Promise<T> {
    return Http.axiosInstance
      .get(url, params)
      .then((res) => res.data)
      .catch();
  }

  public httpRequestPost<T>(
    url: string,
    params: AxiosRequestConfig
  ): Promise<T> {
    return Http.axiosInstance
      .post(url, params)
      .then((res) => res.data)
      .catch();
  }
}

// 创建实例，暴露出去
export const http = new Http();
